package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;

@Configuration
public class RefreshTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 前置拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)){
            return true;
        }

        //基于token在redis中获取session用户
        Map<Object, Object> usermap = redisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        if (usermap.isEmpty()){
            return true;
        }
        User user = BeanUtil.fillBeanWithMap(usermap, new User(), false);

        //存在 保存用户信息到ThreadLocal
        UserHolder.saveUser(user);

        //刷新有效期
        redisTemplate.expire(LOGIN_USER_KEY + token,RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
        //放行
        return true;
    }

    /**
     * 后置拦截 销毁用户信息
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }

}
